﻿#region Header
// ------------------------ Licence / Copyright ------------------------
// 
// ScrumTable for Scrum Meeting Support
// Copyright © HSR - Hochschule für Technik Rapperswil
// All Rights Reserved
// 
// Author:
//  Michael Gfeller Silvan Gehrig Patrick Boos
// 
// ---------------------------------------------------------------------
#endregion

#region Usings

using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Xml;
using Microsoft.TeamFoundation.Server;
using Microsoft.TeamFoundation.WorkItemTracking.Client;

using ScrumTable.Common;
using ScrumTable.Common.Collections;
using ScrumTable.Common.Logging;
using ScrumTable.Common.Monitoring;
using ScrumTable.Common.Xml;
using ScrumTable.DL.Data.Generic.Cache;
using ScrumTable.DL.Data.Schema.ScrumTableV1;

#endregion

namespace ScrumTable.DL.Data.TFS.Bulk.Services.IterationHandling
{
    /// <summary>
    /// This class is used to load all data below a given iteration.
    /// </summary>
    internal class Tfs11IterationLoader : IterationLoaderBase
    {
        #region Declarations
        //--------------------------------------------------------------------
        // Declarations
        //--------------------------------------------------------------------

        private const string IterationStructureNodeTree = "Iteration";

        #endregion

        #region Properties
        //--------------------------------------------------------------------
        // Properties
        //--------------------------------------------------------------------

        #endregion

        #region Constructors / Destructor
        //--------------------------------------------------------------------
        // Constructors / Destructor
        //--------------------------------------------------------------------

        /// <summary>
        /// Creates a new TfsIterationLoader with the associated schema config.
        /// </summary>
        /// <param name="schema">Specifies the schema configuration data.</param>
        internal Tfs11IterationLoader(IterationSchema schema)
            : base(schema)
        {
        }

        #endregion

        #region Methods
        //--------------------------------------------------------------------
        // Methods
        //--------------------------------------------------------------------

        /// <summary>
        /// Loads the iteration data using the strategies of the underlying
        /// derivations.
        /// </summary>
        /// <param name="importMonitor">Specifies the data load monitor which is used to visualize the data import.</param>
        /// <param name="workItemDataLoader">Specifies the work item loader which is used to initialize the CacheWorkItem instances.</param>
        /// <param name="context">Specifies the context with all data which is required to import the data.</param>
        /// <param name="callback">Specifies the callback mechanism method which is used to call the next load part.</param>
        internal override void StartLoadIterationData(IDataImportMonitor importMonitor, WorkItemDataLoader workItemDataLoader, InitialDataCacheLoader.DataLoadContext context, Action<Exception> callback)
        {
            PreCondition.AssertNotNull(importMonitor, "importMonitor");
            PreCondition.AssertNotNull(workItemDataLoader, "workItemDataLoader");
            PreCondition.AssertNotNull(context, "context");
            PreCondition.AssertNotNull(callback, "callback");

            importMonitor.StartSubProgress(IterationLoadPart);

            try
            {
                LoadIterationData(importMonitor, context);
            }
            catch (Exception e)
            {
                importMonitor.EndSubProgress(IterationLoadPart, e);
                callback(e);
            }

            importMonitor.EndSubProgress(IterationLoadPart);
            callback(null);
        }

        private void LoadIterationData(IDataImportMonitor importMonitor, InitialDataCacheLoader.DataLoadContext context)
        {
            List<Node> iterationNodes = new List<Node>();
            LoadIterationsRecursive(iterationNodes, new Dictionary<string, Node>(), context.TfsProject.IterationRootNodes);

            IDictionary<string, IterationNodeData> iterationStructureNodesByUri = TryGetIterationInfo(context);
            DateTime iterationDefaultTime = DateTime.Now;
            int iterationIndex = 0;

            foreach (Node iteration in iterationNodes)
            {
                string iterationPathName = GetIterationPathName(iteration.Path);

                IterationNodeData iterationStructureInfo = iterationStructureNodesByUri.TryGetValue(iteration.Uri.ToString());
                CacheIteration cacheIteration = context.CacheProject.OwnerContext.ElementFactory.CreateIteration(
                    iteration.Uri.ToString(),
                    iteration.Id,
                    iterationIndex,
                    iterationPathName,
                    iteration.Path,
                    (iterationStructureInfo != null) ? iterationStructureInfo.StartDate : iterationDefaultTime,
                    (iterationStructureInfo != null) ? iterationStructureInfo.FinishDate : iterationDefaultTime);

                context.LoadedIterations.Add(cacheIteration);
                importMonitor.ReportProgress(IterationLoadPart, iterationIndex + 1, iterationNodes.Count);
                ++iterationIndex;
            }
        }

        private IDictionary<string, IterationNodeData> TryGetIterationInfo(InitialDataCacheLoader.DataLoadContext context)
        {
            IDictionary<string, IterationNodeData> nodes = new Dictionary<string, IterationNodeData>();

            try
            {
                DateTime defaultTime = DateTime.Now;

                var iterationRootNode = context.TfsContext.StructureService
                    .ListStructures(context.TfsProject.Uri.ToString())
                    .FirstOrDefault(node => node.Name == IterationStructureNodeTree);

                if (iterationRootNode != null)
                {
                    XmlNode allIterationNodes = context.TfsContext.StructureService.GetNodesXml(new[] { iterationRootNode.Uri }, true);

                    if (allIterationNodes != null)
                    {
                        foreach (XmlNode iterationNode in allIterationNodes.SelectNodes("//Node"))
                        {
                            string nodeId = iterationNode.GetAttributeValue("NodeID");

                            DateTime startDate = TryParseDateInvariant(
                                iterationNode.GetAttributeValue("StartDate"),
                                defaultTime);
                            DateTime finishDate = TryParseDateInvariant(
                                iterationNode.GetAttributeValue("FinishDate"),
                                defaultTime);

                            if (!string.IsNullOrEmpty(nodeId))
                            {
                                nodes[nodeId] = new IterationNodeData
                                    {
                                        FinishDate = finishDate,
                                        StartDate = startDate,
                                        Id = nodeId
                                    };
                            }
                        }
                    }
                }
            }
            catch (Exception error)
            {
                Logger<Tfs11IterationLoader>.Warn("", error);
                return null;
            }
            return nodes;
        }

        private DateTime TryParseDateInvariant(string toParse, DateTime defaultDate)
        {
            DateTime parsedDate;
            if (toParse != null &&
                DateTime.TryParse(
                    toParse,
                    DateTimeFormatInfo.InvariantInfo,
                    DateTimeStyles.AssumeLocal,
                    out parsedDate))
            {
                return parsedDate;
            }
            return defaultDate;
        }


        //--------------------------------------------------------------------
        // Nested Classes
        //--------------------------------------------------------------------

        private class IterationNodeData
        {
            #region Properties
            //--------------------------------------------------------------------
            // Properties
            //--------------------------------------------------------------------

            /// <summary>
            /// Gets the 'NodeID' XmlNode content.
            /// </summary>
            internal string Id { get; set; }

            /// <summary>
            /// Gets the 'StartDate' XmlNode content.
            /// </summary>
            internal DateTime StartDate { get; set; }

            /// <summary>
            /// Gets the 'FinishDate' XmlNode content.
            /// </summary>
            internal DateTime FinishDate { get; set; }

            #endregion
        }

        #endregion

        #region Events
        //--------------------------------------------------------------------
        // Events
        //--------------------------------------------------------------------

        #endregion
    }
}